//
//  WHYHeadLineViewController.m
//  News163
//
//  Created by 王洪运 on 15/12/30.
//  Copyright © 2015年 王洪运. All rights reserved.
//

#import "WHYHeadLineViewController.h"
#import "WHYHeadLineCell.h"
#import "WHYHeadLine.h"
#import "SVProgressHUD.h"
#import "WHYHTTPManager.h"
#import "WHYNewsDetailViewController.h"


@interface WHYHeadLineViewController ()

@property (strong, nonatomic) NSArray *headLines;

@end

@implementation WHYHeadLineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loadNews];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
}

#pragma mark - 页面跳转
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
    WHYNewsDetailViewController *newsDetailVC = segue.destinationViewController;
    
    NSUInteger row = self.tableView.indexPathForSelectedRow.row;
    newsDetailVC.headLine = self.headLines[row];
    
    newsDetailVC.hidesBottomBarWhenPushed = YES;
    
}

#pragma mark - 加载数据
-(void)loadNews {
    
    [SVProgressHUD show];
    
    [[WHYHTTPManager manager] loadNewsRequestWithNewsId:self.newsId finishedHandler:^(id result, NSError *error) {
        
        [SVProgressHUD dismiss];
        
        if (error) {
            [SVProgressHUD showErrorWithStatus:@"加载数据出错,请重试"];
            NSLog(@"%@",error);
            return;
        }
        
        self.headLines = [WHYHeadLine headLinesWithDictArray:result[self.newsId]];
        
        [self.tableView reloadData];
    }];
    
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.headLines.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    WHYHeadLine *headLine = self.headLines[indexPath.row];
    
    NSString *cellID = [WHYHeadLineCell headLineCellIdentifierWithHeadLine:headLine];
    
    WHYHeadLineCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
    
    cell.headLine = headLine;
    
    return cell;
}

#pragma mark - Table view Delegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    WHYHeadLine *headLine = self.headLines[indexPath.row];
    return [WHYHeadLineCell headLineCellHeightWithHeadLine:headLine];
}


#pragma mark - 懒加载
-(NSArray *)headLines {
    if (_headLines == nil) {
        _headLines = [NSArray array];
    }
    return _headLines;
}

@end
